In TypeScript, unions and intersections are used to combine multiple types into a single type, allowing you to create more flexible and powerful
type definitions.
- A union type is represented using the pipe symbol
|
. It allows you to declare a variable or parameter that can hold values of
different types. The variable can be assigned a value of any type listed in the union.
- An intersection type is represented using the ampersand symbol
&
. It allows you to combine multiple types into a single type
that includes all the properties and methods from each type.
Having duplicated constituents in TypeScript unions and intersections can lead to undesirable behavior and potential issues in your code.
TypeScript’s type system aims to provide a strong and sound static type checking to catch errors during development and improve code reliability.
Including duplicate constituents in unions or intersections can make the type definitions unnecessarily verbose and redundant. This makes the code
harder to read and maintain.
function padLeft(value: string, padding: string | number | string) { // Noncompliant: 'string' type is used twice in a union type declaration
// ...
}
function extend(p : Person) : Person & Person & Loggable { // Noncompliant: 'Person' is used twice
// ...
}
Define unions and intersections with distinct and non-repeating constituents. This will make your code cleaner and more precise.
function padLeft(value: string, padding: string | number | boolean) {
// ...
}
function extend(p : Person) : Person & Loggable {
// ...
}